package com.kqb.sgauth.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kqb.sgauth.manager.wx.model.pojo.WxMiniProgramsResult;
import com.kqb.sgauth.manager.wx.service.WxMiniProgramsService;
import com.kqb.sgauth.mapper.UserAccountMapper;
import com.kqb.sgauth.model.UserAccount;
import com.kqb.sgauth.service.UserAccountService;
import com.kqb.sgauth.service.WxService;
import com.kqb.sgcommon.base.utils.ThrowUtils;
import com.kqb.sgcommon.satoken.Device;
import com.kqb.sgcommon.satoken.StpKit;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author D
 * @description 针对表【t_user_account(用户基本信息表)】的数据库操作Service实现
 * @createDate 2025-06-14 13:59:59
 */
@Service
public class WxServiceImpl implements WxService {

    @Resource
    private WxMiniProgramsService wxMiniProgramsService;

    @Resource
    private UserAccountService userAccountService;

    @Override
    public SaTokenInfo wxLogin(String code) {
        //通过code得到openid
        WxMiniProgramsResult wxMiniProgramsResult = wxMiniProgramsService.getSessionKey(code);
        String unionid = wxMiniProgramsResult.getUnionid();
        String openid = wxMiniProgramsResult.getOpenid();

        if (openid == null) {
            throw new RuntimeException("小程序登录失败");
        }

        //查看数据库是否存在该用户
        UserAccount oldUserAccount = userAccountService.getUserAccountByOpenId(openid);
        if (oldUserAccount == null) {
            UserAccount userAccount = new UserAccount();
            userAccount.setOpenid(openid);
            userAccount.setUnionid(unionid);
            boolean res = userAccountService.save(userAccount);
            ThrowUtils.throwNotIf(res, new RuntimeException("保存用户信息失败"));
            StpKit.USER.login(openid, Device.MINI_PROGRAM);
        }
        //查看用户是否登录 如果没登录使用openid登录
        boolean isLogin = StpKit.USER.isLogin();
        if (!isLogin) {
            StpKit.USER.login(openid, Device.MINI_PROGRAM);
        }
        return StpKit.USER.getTokenInfo();
    }
}




